<?php

class CommAction extends Action
{
    public function _initialize(){   
        // $this->check_login_Invalid();
        $this->loadConfig();//加载配置项
        $this->check_use_time();//检查是否处于可登录状态
        import('ORG.Util.Session');
        !(MODULE_NAME == 'Login') ? (getLoginUid() == 0 ? $this->getToLogin() : NULL) : NULL;
       
        //获取登陆用户信息
        $this->assign('webtitle', 'mytemplate_tp3模板');
        $uid = getLoginUid();
        $this->check_worker($uid);
        $this->get_admin_menu($uid);
    }

    //定时登录失效
    public  function check_login_Invalid(){
        $login_end_time = M('use_time')->where(array('id'=>1))->getField('login_end_time');
        if($login_end_time < time()){
            $this->redirect('/Admin/Login/login');
        }
    }
    public function loadConfig()
    {
        $tmplParseString = array();
        $tmplParseString['__STATIC__'] = __APP__ . '/static';
        $tmplParseString['__UPLOAD__'] = __APP__ . '/upload';
        $tmplParseString['__PUBLIC__'] = __APP__ . '/public';
        $tmplParseString['__SITE_URL__'] = __APP__;
        C('TMPL_PARSE_STRING', $tmplParseString);
        $this->assign('baseurl',getBaseUrl());
        $this->assign('app',__APP__);
    }

    // 检查是否处于可登录状态
    public function check_use_time(){
        $use_time = M('use_time')->where(array('id'=>1))->getField('use_time');
        if($use_time  < time()){
            // Header("Location: http://www.google.com/chrome/intl/zh-CN/welcome.html");
            $this->redirect('/Admin/Login/miss');
        }
    }

    //检测登陆者是否是在职员工
    public function check_worker($uid = 1){
      $map1['user_id'] = $uid;
      $roleid = M('admin_user_role')->where(array('user_id'=>$uid))->getField('role_id');
      $map2['id'] = $roleid;
      $map2['is_delete'] = 2;
      $admin_info = M('admin_role')->where($map2)->find();
      if($admin_info){
        $this->assign('job',$admin_info['name']);
      }else{
        $this->error('此账号已作废,无法进入后台!',U('Login/login'));
      }
    }
    //后台菜单
    public function get_admin_menu($uid=1){
      $map1['user_id'] = $uid;
      $roleid = M('admin_user_role')->where(array('user_id'=>$uid))->getField('role_id');
      $map2['id'] = $roleid;
      $map2['is_delete'] = 2;
      $admin_info = M('admin_role')->where($map2)->find();
      $map3['role_id'] = $roleid;//获取该登陆者的角色
      $menu_ids = M('admin_role_menu')->where($map3)->getField('menu_id',true);
      //测试结果集
      foreach($menu_ids as $k=>$val){
        $map4['menu_id'] = $val;
        $map4['f_menu_id'] = 0;
        $menusA[] = M('admin_menu')->where($map4)->find();
        $map5['menu_id'] = $val;
        $map5['f_menu_id'] = array('gt',0);
        $menusB[] = M('admin_menu')->where($map5)->find();
        // dump(M()->getLastSql());
      }
      // dump($menusA);
      // dump($menusB);
      $this->assign('menusA',$menusA);
      $this->assign('menusB',$menusB);
    }

    public function getToLogin()
    {
        $this->redirect('/Admin/Login/login');
    }


    public function checkEmpty($value, $content)
    {
        if ($value == null) {
            $this->error($content);
        }
    }
    /**
     * 删除表中的重复数据
     */
    public function delSame(){
        set_time_limit(0);
        $tableName=trim(I('get.tableName'));
        $byField=trim(I('get.byField'));
        if(empty($tableName)){
            echo 'get参数中应该带上表名tableName'.'<br>';
            exit;
        }
        if(empty($byField)){
            echo 'get参数中应该带上字段名byField,根据此字段进行比对'.'<br>';
            exit;
        }
        echo $tableName.'表记录数:'.D($tableName)->count().'<br>';
        echo '开始时间：'.date('Y-m-d H:i:s',time()).'<br>';
        //处理yq_temp表的重复数据
        $tempModel=D($tableName);
        $records=$tempModel->select();
        foreach($records as $key=>$value){
            $data=$value;
            $map=array();
            $map[$byField]=$records[$key][$byField];
            $thisCount=$tempModel->where($map)->count();
            if($thisCount>1)
            {
                $tempModel->where($map)->delete();
                //增加上去一条数据
                $tempModel->data($data)->add();
            }
            //下一条数据
        }
        echo '处理后'.$tableName.'表记录数：'.$tempModel->count().'<br>';
        echo '结束时间：'.date('Y-m-d H:i:s',time()).'<br>';
        echo '结束';
    }
    /**
     * 导出excel文件wps
     */
    public function exportexcel($data = array(), $title = array(), $filename = 'report')
    {
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma:no-cache");
        header("Expires:0");
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                if($type=='excel'){
                    $title[$k]=iconv("UTF-8","GB2312",$v);
                }
                //                
            }
            $title = implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                foreach ($val as $ck => $cv) {
                    if($type=='excel'){
                        $data[$key][$ck]=iconv("UTF-8","GB2312",$cv);    
                    }
                    //                    
                }
                $data[$key] = implode("\t", $data[$key]);
            }
            echo implode("\n", $data);
        }
    }
    /**
     * 导出excel文件office
     */
    public function exportexcel2($data = array(), $title = array(), $filename = 'report')
    {
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma:no-cache");
        header("Expires:0");
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                if($type=='excel'){
                    $title[$k]=iconv("UTF-8","GB2312",$v);
                }
                //                
            }
            $title = implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                foreach ($val as $ck => $cv) {
                    if($type=='excel'){
                        // $data[$key][$ck]=iconv("UTF-8","GB2312",$cv);    
                    }
                    //                    
                }
                $data[$key] = implode("\t", $data[$key]);
            }
            echo implode("\n", $data);
        }
    }
    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * post方法
     */
    function httpPost($url, $data)
    { // 模拟提交数据函数

        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); // 模拟用户使用的浏览器
        // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        // curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }

    /**
     * 获取一个可用的token
     */
    public function getToken()
    {
        $platModel=D('WechatPlat');
        $authInfo=$platModel->find();
        $token=$authInfo['accessToken'];
        $tokenTime=$authInfo['accessTime'];
        $appId=$authInfo['appId'];
        $appSecret=$authInfo['appSecret'];
        if ($tokenTime < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $tokenTime = time() + 7000;
                $token = $access_token;
                //把accesstoken写入数据表
                $authInfo['accessToken']=$token;
                $authInfo['accessTime']=$tokenTime;
                $platModel->data($authInfo)->save();
            }
        }
        return $token;
    }

    /**
     * 通过api获取公众号的粉丝数
     */
    public function getFansCount(){
        $token=$this->getToken();
        $url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=$token";
        $rs=$this->httpGet($url);
        $rs=json_decode($rs,true);
        return $rs['total'];
    }

    /**
     * 统一修改时间格式
     * data:需要更改格式的数组
     * row:需要更改格式的列，多列用逗号隔开
     * format格式化标示
     */
    public function changeTime($data,$format='Y-m-d H:i',$row='createtime'){
        $temp=explode(',',$row);
        foreach($data as $key=>$value){
            if($temp[1]){   //多个列
                foreach($temp as $k=>$v){
                    if(is_numeric($data[$key][$temp[$k]])){
                        $data[$key][$temp[$k]]=date($format,$data[$key][$temp[$k]]);
                    }
                }
            }else{
                $data[$key][$row]=date($format, $data[$key][$row]);
            }
        }
        return $data;
    }

    /**
     * 获取公众号粉丝列表
     */
    public function getWxUserList(){
        $token=$this->getToken();
        $url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=$token";
        $result=$this->httpGet($url);
        $result=json_decode($result,true);
        $userList=$result['data']['openid'];
        $i=0;
        while(count($result['data']['openid'])==10000){
            $i++;
            $next=$result['next_openid'];
            $url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=$token&next_openid=$next";
            $result=$this->httpGet($url);

            $result=json_decode($result,true);
            $userList=array_merge($userList,$result['data']['openid']);
            if($i>=20){
                echo '拉取用户分组接口调用次数太多，粉丝超过20万';
                exit;
            }
        }
        return $userList;
    }


    /**
     * 通过接口获取用户微信信息，参数：openid
     */
    public function getWxUserInfo($openid){
        $token=$this->getToken();
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
        $result=$this->httpGet($url);
        $result=json_decode($result,true);
        $data=$result;
        $data['imgurl']=str_replace("http://wx.qlogo.cn/mmopen/","",$result['headimgurl']);
        $data['createtime']=time();
        $data['score']=0;
        return $data;
    }

    

    /*
    记录管理员操作
     */
    public function addLog($name,$type,$action){
        $data = array();
        $data['adminname'] = D('Admin')->getTrueName(getLoginUid());
        $data['adminid'] = getLoginUid();
        $data['name'] = $name;
        $data['type'] = $type;
        $data['action'] = $action;
        $data['createtime'] = time();
        M('log')->data($data)->add();
    }

    

    /**
     * 公共弹框方法
     */
    public function simpleAlert($content, $url = 'javascript:history.go(-1);')
    {
        echo "<SCRIPT language=JavaScript>alert('$content');return false;</SCRIPT>";
        echo ' ';
        exit;
    }

}